/* eslint-disable no-async-promise-executor */
const model = require("../models/model")
const MyGoodsList = model.goodsdetailsList.MyGoodsList
const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku
const MyGoodsListType = model.goodsdetailsType.MyGoodsListType
const { getFile } = require('../models/getfile')
// const Files = model.files.Files // 获取模型
// require('dotenv').config()
// const { PRO_API, DEV_API } = process.env
// 获取列表
exports.getList = async(ctx) => {
  // console.log(ctx)
  const { goodsId } = ctx.request.query

  function skuDetails(key, value) {
    return new Promise(async(resolve) => {
      function sku_res() {
        return new Promise(async(resolve) => {
          const res = await MyGoodsListSku.findOne({ where: { k_s: key }})
          if (res) {
            resolve(res)
          }
        })
      }
      function type_res() {
        return new Promise(async(resolve) => {
          const res = await MyGoodsListType.findOne({ where: { id: value }})
          if (res) {
            const imgUrl_res = await getFile(res.imgUrl)
            const previewImgUrl_res = await getFile(res.previewImgUrl)
            res.imgUrl = imgUrl_res
            res.previewImgUrl = previewImgUrl_res
            resolve(res)
          }
        })
      }
      Promise.all([sku_res(), type_res()]).then(promise_all => {
        const data = Object.assign(promise_all[1], { k: promise_all[0].k })
        resolve(data)
      })
    })
  }
  function allFn() {
    return new Promise(async(resolve) => {
      let query = {}
      if (goodsId) {
        query = {
          where: {
            parentId: goodsId
          }
        }
      }
      const list_res = await MyGoodsList.findAll(query)
      if (list_res !== undefined && list_res.length > 0) {
        list_res.forEach(item => {
          for (const prop in item) {
            if (!item[prop]) {
              delete item[prop]
            }
          }
        })
        let flagLenth = 0 // 计算有多少个sku
        list_res.forEach(item => {
          for (const prop in item) {
            if (prop.includes('s') && prop.length < 9) { // 计算有多少个sku
              flagLenth++
            }
          }
        })

        let flag = 0
        list_res.forEach(item => {
          for (const prop in item) {
            item['list'] = []
            if (prop.includes('s') && prop.length < 9) {
              skuDetails(prop, item[prop]).then(data => {
                item['list'].push(data)
                flag++
  
                if (flagLenth === flag) { // 全部异步循环完成才返回数据
                  resolve(list_res)
                }
              })
            }
          }
        })
      } else {
        resolve(list_res)
      }
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success(res)
  } else {
    ctx.fail()
  }
}
// 修改或增加
exports.modifyList = async(ctx) => {
  const data = ctx.request.body
  if (!data) {
    ctx.fail('参数错误')
    return
  }
  // 修改规格
  function edit() {
    return new Promise(async(resolve) => {
      // 修改前先查询 表中是否有相同规格的数据（只能修改自身）
      let query = { parentId: data.parentId }
      for (const prop in data) {
        if (prop.includes('s') && prop.length < 9) {
          query[prop] = data[prop]
        }
      }
      const findAllSku = await MyGoodsList.findOne({
        where: query
      })
      console.log(findAllSku, data, query)
      if (findAllSku) { // 找到了相应的数据，看是否与参数id一致（为修改自己本身）
        if (findAllSku.id === data.id) { // 相同为修改自身
          const res = await MyGoodsList.update(data, {where: { id: data.id }})
          if (res[0] == 1) {
            resolve('success')
          } else {
            resolve('修改失败')
          }
        } else { // 不同则已存在
          resolve('该商品已有相同规格')
        }
      } else { // 未找到相同的数据可以直接修改
        const res = await MyGoodsList.update(data, {where: { id: data.id }})
        if (res[0] == 1) {
          resolve('success')
        } else {
          resolve('修改失败')
        }
      }
    })
  }
  // 增加规格
  function add() {
    return new Promise(async(resolve) => {
      // 增加前先判断是否有相同规格
      let query = {
        parentId: data.parentId
      }
      for (const prop in data) {
        if (prop.includes('s') && prop.length < 9) {
          query[prop] = data[prop]
        }
      }
      const findAllSku = await MyGoodsList.findOne({
        where: query
      })
      if (!findAllSku) {
        const res = await MyGoodsList.create(data)
        if (res) {
          resolve('success')
        }
      } else {
        resolve('该商品已有相同规格')
      }
    })
  }

  let res
  if (data.id) {
    res = await edit()
  } else {
    res = await add()
  }
  if (res === 'success') {
    ctx.success('', `${data.id ? '修改' : '增加'}成功`)
  } else {
    ctx.fail(res)
  }
}

// 删除规格列表
exports.deleteList = async(ctx) => {
  const { ids } = ctx.request.query
  if (!ids) {
    ctx.fail('参数错误')
    return
  }
  let idsList = ids.split(',')
  function allFn() {
    return new Promise(async(resolve) => {
      let flag = 0
      idsList.forEach(item => {
        MyGoodsList.destroy({ where: { id: item }}).then(res => {
          flag++
          if (flag === idsList.length) {
            resolve(res)
          }
        })
      })
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success('', `删除成功`)
  } else {
    ctx.fail('删除失败')
  }
}
